//
//  SearchViewController.m
//  A段项目音乐播放
//
//  Created by dllo on 15/5/25.
//  Copyright (c) 2015年 lanou3g.com蓝鸥科技. All rights reserved.
//


#import "SearchViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "SearchModel.h"

#import "MainViewController.h"
#import "SingerModel.h"
#import "playViewController.h"
#import "SearchDB.h"
#import "Searchdatabase.h"
#import "HistoryCell.h"
@interface SearchViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic,retain)UISearchBar *searchBar;

@property (nonatomic,retain)UITableView *tableSong;
@property (nonatomic,retain)UITableView *tableSinger;
@property (nonatomic,retain)UITableView *tableAlbum;
@property (nonatomic,retain)UITableView *tableMV;
@property (nonatomic,retain)UITableView *tableHistory;

@property (nonatomic,retain)UIScrollView *scroll;
@property (nonatomic,retain)UIView *viewSmall;
@property (nonatomic,retain)UIView *topView;
@property (nonatomic,retain)UIView *viewHistory;
@property (nonatomic,retain)NSMutableArray *modelArray;
@property (nonatomic,retain)NSMutableArray *historyArray;

@property (nonatomic,retain)NSString *historyStr;
@end

@implementation SearchViewController
- (void)dealloc
{
    [_historyArray release];
    [_modelArray release];
    [_tableAlbum release];
    [_tableMV release];
    [_tableSinger release];
    [_tableSong release];
    [_tableHistory release];
    [_scroll release];
    [_viewSmall release];
    [_topView release];
    [_searchBar release];
    [_historyStr release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.modelArray = [NSMutableArray array];
        self.historyArray = [NSMutableArray array];
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //让导航栏隐藏
    self.navigationController.navigationBarHidden = YES;
    
    [self takeout];
    
    [self create]; //创建seachbar, buttonserch

    [self createView];
    [self createTableHistory];
}

- (void)createView
{
    self.viewHistory = [[UIView alloc]initWithFrame:CGRectMake(0, 60, self.view.frame.size.width, self.view.frame.size.height)];
//    [self.viewHistory setBackgroundColor:[UIColor redColor]];
    [self.view addSubview:_viewHistory];
    
}


//创建了四个tableview

- (void)createTableSong
{
    self.tableSong = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.scroll addSubview:self.tableSong];
    self.tableSong.dataSource = self;
    self.tableSong.delegate = self;
    [self.tableSong registerClass:[UITableViewCell class] forCellReuseIdentifier:@"songcell"];
    [self.tableSong release];
}

- (void)createTableSinger
{
    self.tableSinger = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.scroll addSubview:self.tableSinger];
    self.tableSinger.dataSource = self;
    self.tableSinger.delegate = self;
    [self.tableSinger registerClass:[UITableViewCell class] forCellReuseIdentifier:@"singercell"];
    [self.tableSinger release];
}

//- (void)createTableAlume
//{
//    self.tableAlbum = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 2, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
//    [self.scroll addSubview:self.tableAlbum];
//    self.tableAlbum.dataSource = self;
//    self.tableAlbum.delegate = self;
//    [self.tableAlbum registerClass:[UITableViewCell class] forCellReuseIdentifier:@"albumcell"];
//    [self.tableAlbum release];
//}

//- (void)createTableMV
//{
//    self.tableMV = [[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.size.width * 3, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
//    [self.scroll addSubview:self.tableMV];
//    self.tableMV.dataSource = self;
//    self.tableMV.delegate = self;
//    [self.tableMV registerClass:[UITableViewCell class] forCellReuseIdentifier:@"mvclass"];
//    [self.tableMV release];
//}

- (void)createTableHistory
{
//    SearchModel *model = [[SearchModel alloc]init];
    NSArray *array = [Searchdatabase selectAll];
    if (![array count] == 0) {
        
        self.tableHistory = [[UITableView alloc]initWithFrame:CGRectMake(0, 10, self.viewHistory.frame.size.width,self.viewHistory.frame.size.height - 64 * 2) style:UITableViewStylePlain];
        self.tableHistory.dataSource = self;
        self.tableHistory.delegate = self;
        [self.tableHistory registerClass:[UITableViewCell class] forCellReuseIdentifier:@"historyclass"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button setTitle:@"清除历史记录" forState:UIControlStateNormal];
        [button setFrame:CGRectMake(0, 0, 100, 30)];
        [button addTarget:self action:@selector(buttonSweep:) forControlEvents:UIControlEventTouchUpInside];
        
        self.tableHistory.tableFooterView = button;
        self.tableHistory.separatorStyle = UITableViewCellEditingStyleNone;
        [self.viewHistory addSubview:self.tableHistory];
        [self.tableHistory release];
    }
    
}

- (void)buttonSweep:(id)sender
{
    SearchModel *model = [[SearchModel alloc]init];
    NSArray *array =[Searchdatabase selectAll];
    for (int i = 0; i < [array count]; i ++) {
        model = [array objectAtIndex:i];
        [Searchdatabase deleteWithModel:model];
    }
    [self.viewHistory setHidden:YES];
    
}

//    [self.tableArray addObject:self.tableSong];
//    [self.tableArray addObject:self.tableSinger];
//    [self.tableArray addObject:self.tableAlbum];
//    [self.tableArray addObject:self.tableMV];

//    for (int i = 0; i < [self.tableArray count]; i ++) {
//        UIView *viewBig = [[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width * i, 0, self.view.frame.size.width, self.view.frame.size.height)];
//        [viewBig addSubview:[self.tableArray objectAtIndex:i]];
//        [self.scroll addSubview:viewBig];
//        [viewBig release];


// 创建 scrollview 和 4 个button 和 蓝色移动小条
- (void)createScroll
{
    
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 70, self.view.frame.size.width, 30)];
    
    self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height - 200)];
    self.scroll.contentSize = CGSizeMake(self.view.frame.size.width * 2, 0);
    self.scroll.contentOffset = CGPointMake(0, 0);
    self.scroll.pagingEnabled = YES;
    self.scroll.delegate = self;
    [self.view addSubview:self.scroll];
    
    NSArray *array = @[@"歌曲",@"歌手"];
    for (int i = 0; i < [array count]; i ++) {
        NSString *str = [array objectAtIndex:i];
        
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(i * 180, 0, 180, 28)];
        [button setTitle:str forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:0.5] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i + 1;
        [topView addSubview:button];
    }
    
    self.viewSmall = [[UIView alloc]initWithFrame:CGRectMake(0, 28, 180, 2)];
    self.viewSmall.backgroundColor = [UIColor blueColor];
    
    [topView addSubview:self.viewSmall];
    [self.view addSubview:topView];
    
}


// 创建 searchbar , 创建buttonsearch
- (void)create
{

    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(40, 30, 295, 30)];
    self.searchBar.layer.cornerRadius = 10;
    self.searchBar.layer.borderWidth = 2;
    self.searchBar.layer.borderColor = [UIColor grayColor].CGColor;
//        self.searchBar.backgroundColor = [UIColor colorWithRed:0.2 green:0.5 blue:0.3 alpha:0.5];
    self.searchBar.placeholder = @"请输入要搜索的歌手/歌曲";
    self.searchBar.delegate = self;
    self.searchBar.barStyle = UIBarStyleDefault;
//    self.searchBar.keyboardType = UIKeyboardTypeNamePhonePad;
//    self.searchBar.keyboardType = UIKeyboardAppearanceAlert;
    [self.view addSubview:_searchBar];
    
    
    UIButton *buttonSearch = [[UIButton alloc]initWithFrame:CGRectMake(340, 30, 30, 30)];
    UIImage *image = [UIImage imageNamed:@"搜.png"];
    [buttonSearch setImage:image forState:UIControlStateNormal];
    [buttonSearch addTarget:self action:@selector(searchBarSearchButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonSearch];
    
    
    UIButton *buttonBack = [[UIButton alloc]initWithFrame:CGRectMake(5, 30, 35, 30)];
    UIImage *imagea = [UIImage imageNamed:@"返回.png"];
    [buttonBack setImage:imagea forState:UIControlStateNormal];
    [buttonBack addTarget:self action:@selector(buttonBack:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:buttonBack];
}


- (void)buttonBack:(id)sender
{

    NSLog(@"我爱罗");
//    UIViewController *con = [self.navigationController.viewControllers objectAtIndex:0];
    self.navigationController.navigationBarHidden = NO;
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    self.navigationController.navigationBarHidden = NO;
}


// button 的点击事件
- (void)buttonAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    self.scroll.contentOffset = CGPointMake((button.tag - 1) * [UIScreen mainScreen].bounds.size.width, 0);
    NSLog(@"%ld", button.tag);
    
    [UIView animateWithDuration:0.1 animations:^{
        [self.viewSmall setFrame:CGRectMake(180 * (button.tag - 1), 28, 180, 2)];
    }];
    
    if (!self.modelArray.count == 0) {
        if (self.scroll.contentOffset.x == 0) {
            [self createTableSong];
        }
        if (self.scroll.contentOffset.x == self.view.frame.size.width) {
            [self createTableSinger];
        }
//        if (self.scroll.contentOffset.x == self.view.frame.size.width * 2) {
//            [self createTableAlume];
//        }
    }
}


// scrollview 的 彻底停止 协议
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 结束 减速
    
    [UIView animateWithDuration:0.05 animations:^{
        [self.viewSmall setFrame:CGRectMake(180 * (self.scroll.contentOffset.x / self.view.frame.size.width) , 28, 180, 2)];
    }];
    
    if (!self.modelArray.count == 0) {
        if (self.scroll.contentOffset.x == 0) {
            [self createTableSong];
        }
        if (self.scroll.contentOffset.x == self.view.frame.size.width) {
            [self createTableSinger];
        }
//        if (self.scroll.contentOffset.x == self.view.frame.size.width * 2) {
//            [self createTableAlume];
//        }
    }
}


// 点击空白处  收回键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


// searchBar 的协议  网络请求
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"xx");
    NSLog(@"%@",self.searchBar.text);
    
    if ([self.searchBar.text isEqualToString:@""]) {
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请重新输入" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"好",nil];
        [alert show];
        [self.view addSubview:alert];
    }else{
        
        SearchModel *model = [[SearchModel alloc]init];
        model.singer_name = self.searchBar.text;  //mm没必要
        [Searchdatabase insertWithmodel:model];
//        [Searchdatabase insertWithString:self.searchBar.text];
        
    // 字符串 拼接
    NSString *str = [NSString stringWithFormat:@"http://so.ard.iyyin.com/s/song_with_out?q=%@&page=1&size=100", self.searchBar.text];
    
    NSString *address = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    // 网络请求
    AFHTTPSessionManager *mamager = [AFHTTPSessionManager manager];
    mamager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [mamager GET:address parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"success");
        
        self.modelArray = [NSMutableArray array];
        NSData *data = [NSData dataWithData:responseObject];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       NSArray * arrayData = [dic objectForKey:@"data"];
        
        for (NSDictionary *smallDic in arrayData) {
            SingerModel *model = [[SingerModel alloc]init];
            [model setValuesForKeysWithDictionary:smallDic];
            
            NSArray *arrayMv = [smallDic objectForKey:@"audition_list"];
            NSInteger inte = [arrayMv count];
            if (inte != 0) {   ////回来解释
                
                NSDictionary *dicc = [arrayMv objectAtIndex:inte - 1];
                NSString * time = [dicc objectForKey:@"duration"];
                NSArray *array = [time componentsSeparatedByString:@":"];
                NSInteger min = [[array objectAtIndex:0] integerValue];
                NSInteger second = [[array objectAtIndex:1] integerValue];
                NSInteger inter = ((min * 60) + second) * 1000;
                NSString *newdur = [NSString stringWithFormat:@"%ld", inter];
                [model setValuesForKeysWithDictionary:dicc];
                [model setValue:newdur forKey:@"duration"];
                [self.modelArray addObject:model];
                [model release];
            }
        }
        
        [self.viewHistory setHidden:YES];
        [self createScroll];
        [self createTableSong];
        
        
    }failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"failure");
    }];
        
    }
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    NSLog( @"did begin editing");
}

// tableView 的协议

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.tableSinger == tableView) {
        return 1;
    }
    if (self.tableSong == tableView) {
        return [self.modelArray count];
    }
    if (self.tableAlbum == tableView) {
        return [self.modelArray count];
    }
    if (self.tableHistory == tableView) {
        return [self.historyArray count];
    }
    return [self.historyArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.tableSong == tableView) {
        SingerModel *model = [self.modelArray objectAtIndex:indexPath.row];
        UITableViewCell *cellSong = [tableView dequeueReusableCellWithIdentifier:@"songcell"];
        cellSong.textLabel.text = model.name;
        return cellSong;
    }
    
   if (self.scroll.contentOffset.x == self.view.frame.size.width) {
        SingerModel *model = [self.modelArray objectAtIndex:indexPath.row];
        UITableViewCell *cellSinger = [tableView dequeueReusableCellWithIdentifier:@"singercell"];
        cellSinger.textLabel.text = model.singerName;
        return cellSinger;
    }
    
    if (self.scroll.contentOffset.x == self.view.frame.size.width * 2) {
        SingerModel *model = [self.modelArray objectAtIndex:indexPath.row];
        UITableViewCell *cellAlume = [tableView dequeueReusableCellWithIdentifier:@"alumecell"];
        cellAlume.textLabel.text = model.albumName;
        return cellAlume;
    }
    else if (self.tableHistory == tableView){
        HistoryCell *cellDown = [tableView dequeueReusableCellWithIdentifier:@"historycell"];
        if (!cellDown) {
            cellDown = [[HistoryCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"historycell"];
        }
        SearchModel *model = [self.historyArray objectAtIndex:indexPath.row];
        cellDown.label.text = model.singer_name;
//        self.historyStr = cellDown.textLabel.text;
        return cellDown;
    }

    return nil;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
//    if (tableView == self.tableHistory) {
    
        cell.frame = CGRectMake(-320, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        
        [UIView animateWithDuration:0.7 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        } completion:^(BOOL finished) {
            ;
        }];

//    }
    
    //    CATransform3D rotation;
    //    rotation = CATransform3DMakeRotation( (20.0*M_PI)/180, 0.0, 0.7, 0.4);
    //    rotation.m33 = 0.1;
    //
    //    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    //    cell.layer.shadowOffset = CGSizeMake(10, 10);
    //    cell.alpha = 0;
    //    cell.layer.transform = rotation;
    //    cell.layer.anchorPoint = CGPointMake(0, 0.5);
    //
    //
    //    [UIView beginAnimations:@"rotation" context:NULL];
    //    [UIView setAnimationDuration:1];
    //    cell.layer.transform = CATransform3DIdentity;
    //    cell.alpha = 1;
    //    cell.layer.shadowOffset = CGSizeMake(0, 0);
    //    [UIView commitAnimations];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableSong) {
        playViewController *play = [playViewController shareStateOfViewcontroller];
        
        [play playWithModel:self.modelArray index:indexPath.row];
        
//        [self.view removeFromSuperview];
//        self.navigationController
        [self.navigationController presentViewController:play animated:YES completion:nil];
        
    }
    if (tableView == self.tableSinger) {
        
    }
    if (tableView == self.tableAlbum) {
        
    }
    if (tableView == self.tableHistory) {

        SearchModel *model = [self.historyArray objectAtIndex:indexPath.row];
        self.searchBar.text = model.singer_name;
        [self searchBarSearchButtonClicked:self.searchBar];
        
    }
    
}


- (void)takeout
{
    NSArray *array = [NSMutableArray array];
    array = [Searchdatabase selectAll];
    [self.historyArray addObjectsFromArray:array];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
